#include "../ep_poller.h"
#include "../log_warper.h"
#include "../io_channel.h"

ep_poller::ep_poller()
{
    //ctor
}

ep_poller::~ep_poller()
{
    //dtor
}
x_fd    ep_poller::create_ep_fd(x_int32 max_fd)
{
    return  ::epoll_create( max_fd);
}

x_int32     ep_poller::get_event(io_channel_raw_ptr_vec& channels,x_int32 timeout_ms )
{
    ep_event_t      evt_got[max_event_for_poll_];
    x_int32         number_of_evt_ready = ::epoll_wait(m_epoll_fd,&evt_got[0],max_event_for_poll_,timeout_ms);
    if( 0 < number_of_evt_ready ) {
        for(x_int32 loop = 0;loop < number_of_evt_ready; ++loop){
            io_channel* the_channel = static_cast<io_channel*>(evt_got[loop].data.ptr);
            BOOST_ASSERT (NULL != the_channel);
            the_channel->evt_handle_flag = evt_got[loop].events;
            channels.push_back(the_channel);
        }
    }else if( 0 == number_of_evt_ready){
        info_loger.stream()<< " epoll_wait got nothing,timeout_ms = "<< timeout_ms;
    }else{
        char err_msg[256];
        err_loger.stream()<< " epoll_wait error,timeout_ms = "<< timeout_ms << " errno = " << errno << " msg = "<< ::strerror_r( errno,err_msg,sizeof(err_msg));
    }
    return number_of_evt_ready;
}
x_int32 ep_poller::update_channel(io_channel*  channel)
{
    BOOST_ASSERT (NULL != channel);
    BOOST_ASSERT (-1 != channel->get_fd());
    ep_event_t evt;
    evt.data.ptr=channel;
    evt.data.events=channel->evt_handle_flag();
    if( 0 !=  ::epoll_ctl(m_epoll_fd, channel->evt_manage_flag(),channel->get_fd(),&evt)){
        char err_msg[256];
        err_loger.stream()<< " epoll_ctl error, errno = " << errno << " msg = "<< ::strerror_r( errno,err_msg,sizeof(err_msg));
        return -1;
    }else{
        return 0;
    }
}

x_int32 ep_poller::update_subscribe_evt(io_channel*  channel)
{
    BOOST_ASSERT (NULL != channel);
    ep_event_t evt;
    evt.data.ptr=channel;
    evt.data.events=channel->evt_handle_flag();
    if( 0 !=  ::epoll_ctl(m_epoll_fd, channel->evt_manage_flag(),channel->get_fd(),&evt)){
        char err_msg[256];
        err_loger.stream()<< " epoll_ctl error, errno = " << errno << " msg = "<< ::strerror_r( errno,err_msg,sizeof(err_msg));
        return -1;
    }else{
        return 0;
    }
}


x_int32 ep_poller::poll_with_guard(io_channel_raw_ptr_vec& channels,x_int32 timeout_ms)
{
//
return -1;
}
x_int32 ep_poller::poll(io_channel_raw_ptr_vec& channels,x_int32 timeout_ms)
{
//
return -1;
}
